package psnl.bingo.bgtool.model.controller;

import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import psnl.bingo.bgtool.framework.dto.UniResult;
import psnl.bingo.bgtool.model.dto.RenameSet;
import psnl.bingo.bgtool.model.dto.TDParam;
import psnl.bingo.bgtool.model.util.FileTool;
import psnl.bingo.bgtool.model.util.TDTool;

import javax.servlet.http.HttpSession;

@Slf4j
@Controller
@RequestMapping("/tableData")
public class TableData {
    @RequestMapping("/index")
    public String pageDefault(HttpSession session, ModelMap model) {
        return "tableData";
    }

    @RequestMapping("/execute")
    @ResponseBody
    public UniResult svUpDingSet(@RequestBody JSONObject param) {
        if(TDParam.isDoing) {
            return UniResult.failure("已有任务在执行");
        }

        System.out.println(param);

        TDParam tdParam = TDTool.checkParam(param);
        if(tdParam.err != null && tdParam.err.length() > 0) {
            TDParam.isDoing = false;
            TDParam.progress = "";
            return UniResult.failure(tdParam.err);
        }

        new Thread(()->{
            try {
                TDTool.handleData(tdParam);
                TDParam.progress = "执行成功";
            } catch (Exception e) {
                e.printStackTrace();
                TDParam.progress = "执行失败："+e.getMessage();
            }finally {
                TDParam.isDoing = false;
            }
        }).start();

        return UniResult.success(TDParam.progress);
    }

    @RequestMapping("/queryState")
    @ResponseBody
    public UniResult queryState() {
        return UniResult.success(TDParam.progress);
    }
}
